package main

import (
	"flag"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	_ "net/http/pprof"
	"os"
	"strings"
	"time"

	"github.com/golang/glog"
	"github.com/prometheus/client_golang/prometheus/promhttp"

	"github.com/cncamp/golang/httpserver/metrics"
)

func main() {
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")
	metrics.Register()

	mux := http.NewServeMux()
	mux.HandleFunc("/hello", rootHandler)
	//mux.HandleFunc("/healthz", healthz)
	mux.Handle("/metrics", promhttp.Handler())

	addr := ":80"
	http.HandleFunc("/header/", func(w http.ResponseWriter, r *http.Request) {

		// 3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出
		fmt.Println(strings.Repeat("-", 10))
		fmt.Println("method:", r.Method)
		fmt.Println("url: ", r.URL)
		fmt.Println("proto: ", r.Proto)
		fmt.Println("host: ", r.Host)

		// 1.接收客户端 request，并将 request 中带的 header 写入 response header
		io.WriteString(w, "===================Details of the http request header:============\n")
		for k, v := range r.Header {
			// fmt.Println(k, v)
			io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
		}
		//2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
		var GOVERSION string = os.Getenv("GOVERSION")
		io.WriteString(w, GOVERSION)
	})

	//4.当访问 localhost/healthz 时，应返回200
	http.HandleFunc("/healthz/", func(w http.ResponseWriter, r *http.Request) {
		io.WriteString(w, "200")
	})

	http.ListenAndServe(addr, nil)

//func healthz(w http.ResponseWriter, r *http.Request) {
//	io.WriteString(w, "ok\n")
//}

}

func randInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	glog.V(4).Info("entering root handler")
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	user := r.URL.Query().Get("user")
	delay := randInt(0, 2000)
	time.Sleep(time.Millisecond * time.Duration(delay))
	if user != "" {
		io.WriteString(w, fmt.Sprintf("hello [%s]\n", user))
	} else {
		io.WriteString(w, "hello [stranger]\n")
	}
	io.WriteString(w, "===================Details of the http request header:============\n")
	for k, v := range r.Header {
		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
	}
	glog.V(4).Infof("Respond in %d ms", delay)
}


